package com.xy.bizportdemo.engine;

import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;

import com.xy.bizportdemo.database.SmsDBHelper;
import com.xy.bizportdemo.database.entity.SmsDBTableMessage;

/**
 * Created by XIAOYUAN on 2016/11/24.
 */

public class MessageLoadEngine extends BaseEngine{
    private static final String TAG = "MessageLoadEngine";
    private String mPhoneNumber = null;

    public MessageLoadEngine(Context context) {
        super(context);
    }

    private void querySms() {
        StringBuffer where = new StringBuffer();
        String[] args = null;
        if (!TextUtils.isEmpty(mPhoneNumber)) {
            where.append(" address=? ");
            args = new String[] {mPhoneNumber};
        }

        try {
            Cursor cursor = mContext.getContentResolver().query(SmsDBHelper.URI_MESSAGE, null, where.toString(), args, "date " +
                    "asc" + "," + SmsDBTableMessage.KEY_ID + " asc");
            if (cursor != null && cursor.moveToFirst()) {
                if (mSmsReadListener != null) {
                    mSmsReadListener.onSmsReadFinished(cursor);
                }
            } else {
                if (mSmsReadListener != null) {
                    mSmsReadListener.onSmsReadError("query fail");
                }
            }
        } catch (Throwable t) {
            Log.e(TAG, "doInBackGround", t);
            if (mSmsReadListener != null) {
                mSmsReadListener.onSmsReadError(t.getMessage());
            }
        }
    }

    public void startReadSms(String phoneNum, SmsReadListener listener) {
        this.mSmsReadListener = listener;
        this.mPhoneNumber = phoneNum;

        new Thread(new Runnable() {
            @Override
            public void run() {
                querySms();
            }
        }).start();
    }
}
